package com.ophiux.wechat.schedule;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ophiux.wechat.mapper.OphiuxOrderRegisterMapper;
import com.ophiux.wechat.model.OphiuxOrderRegisterDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@EnableScheduling
public class ScheduleTask {

	@Value("${wechat.appid}")
	private String appid;
	@Value("${wechat.secret}")
	private String secret;

	@Value("${wechat.templateId}")
	private String templateId;


	@Autowired
	OphiuxOrderRegisterMapper ophiuxOrderRegisterMapper;

	@Scheduled(cron = "0 00 17 * * ?")
	public void sendNotify() {
//		if(LocalDateTime.now().isBefore(LocalDateTimeUtil.parse("2023-05-11 23:59:59",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))){
//			log.info("当前时间 < 2023-05-06 23:59:59不执行定时任务");
//			return;
//		}

		log.info("定时发送满意度评价============开始=============");
		long startTime = System.currentTimeMillis();
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
		String tokenStr = HttpUtil.post(url, "");
		JSONObject object = JSON.parseObject(tokenStr);
		if (!ObjectUtils.isEmpty(object.getString("errcode"))) {
			log.info("获取accessToken失败，{}", tokenStr);
			return;
		}
		String accessToken = object.getString("access_token");
		System.out.println(accessToken);

		String pushUrl = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", accessToken);
		List<OphiuxOrderRegisterDto> list = ophiuxOrderRegisterMapper.getYestDayOrderRegisterList();
		for (OphiuxOrderRegisterDto dto : list) {
			try {
				Map dataMap = new HashMap();
				dataMap.put("touser", dto.getOtherId());
				dataMap.put("template_id", templateId);
				dataMap.put("url", "http://wx.hongrenyiyuan.com:8916/HospWechatMVC/oauthNew/wechat?moduleURL=/oauthNew/oauth-login?logSucUrl=/appointrecord/message-evaluate?id=" + dto.getId());
				Map dynamicDataMap = new HashMap();
				dataMap.put("data", dynamicDataMap);

				Map keyword1Map = new HashMap();
				keyword1Map.put("value", dto.getVisitDate());
				dynamicDataMap.put("keyword1", keyword1Map);

				Map keyword2Map = new HashMap();
				keyword2Map.put("value", dto.getDeptName());
				dynamicDataMap.put("keyword2", keyword2Map);

				Map keyword3Map = new HashMap();
				keyword3Map.put("value", "为了更好的提供服务，就诊结束后，请您评价下医生的就诊服务。");
				dynamicDataMap.put("keyword3", keyword3Map);

				log.info("发送模板消息 {} {} {}", pushUrl, System.lineSeparator(), JSONUtil.toJsonStr(dataMap));
				String result = HttpUtil.post(pushUrl, JSON.toJSONString(dataMap));
				log.info("发送模板消息 结果 {}", result);

			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		long endTime = System.currentTimeMillis();
		log.info("发送模板消息 用时{}毫秒", endTime - startTime);
	}
}